<?php

namespace App\Http\Controllers;

use App\Test1221;
use Illuminate\Http\Request;
use Qiniu\Storage\UploadManager;
use Qiniu\Auth;
class Test1221Controller extends Controller
{
    /**
     * 后台添加页面
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function add(){
        return view('test1221add');
    }

    /**
     * 数据添加方法
     * @param Request $request
     */
    public function adddo(Request $request){
        $data['title']   = $request['title'];
        $data['author']  = $request['author'];
        $data['image']    = $request->file('file')->store('idcard');

        $accessKey = 'V-UrKPzffOoIvZ-fc1ktq0lM87OKO1kYUn1GXuvE';
        $secretKey = '5lz9V83iKYcxBT1xucxaLl4TLiZKX-VqfwcVcL4p';
        $bucket = 'zxpdehao';
        $uploadMgr = new UploadManager();
        $auth = new Auth($accessKey, $secretKey);
        $token = $auth->uploadToken($bucket);
        list($ret, $error) = $uploadMgr->putFile($token, $data['image'], $data['image']);

        $data['content'] = $request['content'];
        $res = Test1221::insert($data);
        if($res){
            echo "添加成功";
        }else{
            echo '添加失败';
        }
    }

    /**
     * 获取数据接口
     * @return array
     */
    public function getAll(){
        $data = Test1221::get()->toArray();
        foreach($data as $key=>$value){
            $data[$key]['image'] = 'http://www.cms.com/'.$value['image'];
        }
        return ['data'=>$data,'code'=>0,'msg'=>'成功'];
    }

    /**
     * 获取一条数据接口
     * @param Request $request
     * @return array
     */
    public function getOne(Request $request){
        $where['id'] = $request['id'];
        $data = Test1221::where($where)->first()->toArray();
        $data['image'] = 'http://www.cms.com/'.$data['image'];
        if($data){
            return ['data'=>$data,'code'=>0,'msg'=>'成功'];
        }else{
            return ['data'=>'','code'=>1,'msg'=>'失败'];
        }
    }
}
